package com.atguigu.yygh.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.atguigu.yygh.common.utils.R;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@Component
public class LoginFilter implements GlobalFilter , Ordered {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    //验证是否登录
    //判断请求头是否有X-token
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //获取请求路径
        String path = exchange.getRequest().getURI().getPath();
        //路径匹配器

        //不是登录的请求才验证
        if(!antPathMatcher.match("/**/login",path)) {
            List<String> list = exchange.getRequest().getHeaders().get("X-Token");
            //未登录,拦截请求

            if (list == null) {

                return out(exchange);
            }
        }
        //放行
        return chain.filter(exchange);

    }



    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> out(ServerWebExchange exchange) {

        R result=R.error().message("未登录-鉴权失败");
        byte[] bits = JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        ServerHttpResponse response = exchange.getResponse();
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
